/*
	Copyright (c) 2009, SpLib.net
  	All rights reserved.
  	
  	Author:6spring
  	About:链表
*/

package SpLib.std
{
	import SpLib.std.iterator;
	
	public class list
	{
		private var m_pHead:iterator = null;
		private var m_pTail:iterator = null;
		private var m_nSize:int = 0;
		
		public function list()
		{
		}
		
		public function size():int
		{
			return m_nSize;
		}
		
		public function empty():Boolean
		{
			return m_nSize==0;
		}

		public function front():*
		{
			if(m_pHead==null)
			{
				return null;
			}
			
			return m_pHead.m_Data;
		}
		
		public function back():*
		{
			if(m_pTail==null)
			{
				return null;
			}
			
			return m_pTail.m_Data;
		}
		
		public function begin():iterator
		{
			if(m_pHead==null)
			{
				return null;
			}
			else
			{
				return m_pHead;
			}
		}
		
		public function rbegin():iterator
		{
			if(m_pTail==null)
			{
				return null;
			}
			else
			{
				return m_pTail;
			}
		}
		
		public function end():iterator
		{
			return null;
		}
		
		public function clear():void
		{
			while(m_nSize>0)
				pop_back();
		}
		
		public function push_back(data:*):void
		{
			var node:iterator = new iterator(data);
			
			if(m_nSize==0)
			{
				m_pHead = m_pTail = node;
			}
			else
			{
				m_pTail.next = node;
				m_pTail = node;
			}
			
			m_nSize++;
		}
		
		public function push_front(data:*):void
		{
			var node:iterator = new iterator(data);
			
			if(m_nSize==0)
			{
				m_pHead = m_pTail = node;
			}
			else
			{
				m_pHead.prev = node;
				m_pHead = node;
			}
			
			m_nSize++;
		}
		
		public function pop_back():void
		{
			if(m_nSize==0) return;
			
			var tail:iterator = m_pTail;
			
			if(m_nSize>1)
			{
				var newtail:iterator = m_pTail.prev;
				newtail.next = null;
				m_pTail = newtail;
			}
			else
			{
				m_pHead = m_pTail = null;
			}
			
			m_nSize--;
			tail.release();
		}
		
		public function pop_front():void
		{
			if(m_nSize==0) return;
			
			var head:iterator = m_pHead;
			if(m_nSize>1)
			{
				var newhead:iterator = m_pHead.next;
				newhead.prev = null;
				m_pHead = newhead;
			}
			else
			{
				m_pHead = m_pTail = null;
			}
			
			m_nSize--;
			head.release();
		}
		
		public function erase(node:iterator):iterator
		{
			if(m_nSize==0) return null;
			
			var iter:iterator = m_pHead;
			while(iter!=null)
			{
				if(iter===node)
				{
					if(m_pHead===iter)
					{
						m_pHead = iter.next;
					}
					
					if(m_pTail===iter)
					{
						m_pTail = iter.prev;
					}
					
					var next:iterator = iter.next;
					iter.release();
					m_nSize--;
					
					if(m_nSize==0)
					{
						m_pHead = m_pTail = null;
					}
					
					return next;
				}
				
				iter = iter.next;
			}
			
			return null;
		}
	}
}